package com.foodlocker.courier;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.foodlocker.bean.Courier;
import com.foodlocker.bean.Order;
import com.foodlocker.common.CommonFunction;
import com.foodlocker.common.Constant;
import com.foodlocker.common.ListViewUtil;
import com.foodlocker.common.UniversalHttpPost;

import com.foodlocker.machine.Box;
import com.foodlocker.machine.R;
import com.foodlocker.sqlite.OrderDao;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class TakebackAct extends Activity { 

	JSONArray orderJA= new JSONArray();
	ListView abandomOrderList;
	Button confirm;
	RelativeLayout  rt_shadow;
	TextView tv_hint;
	String AFFAIR_TAKEBACK_ORDER="orderTakeback";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.act_takeback);	
		abandomOrderList= (ListView) findViewById(R.id.list_acttakebackorder);
		confirm= (Button) findViewById(R.id.btn_confirm_acttakebackorder);
		rt_shadow= (RelativeLayout) findViewById(R.id.rt_shadow_acttakebackorder);
		rt_shadow.setVisibility(View.GONE);
		tv_hint= (TextView) findViewById(R.id.tv_nethint_acttakebackorder);
		orderJA= new OrderDao(this).queryTakebackOrder();
		abandomOrderList.setAdapter(new ParentListAdapter(this));
		if(orderJA.size()==0){
			 Intent intent= new Intent(TakebackAct.this, AbandomAct.class);
		      startActivity(intent);
		      TakebackAct.this.finish();
		}
		confirm.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String[] params= new String[3];
		         params[0]=Constant.BaseUrl+Constant.MachineUrl;
		         params[1]=AFFAIR_TAKEBACK_ORDER; //PostCod
		         JSONObject jsonData=new JSONObject();
		         jsonData.put("machine", Constant.machineJO);
		         jsonData.put("orders",orderJA);
		         jsonData.put("courier",Constant.courierJO.getString(Courier.TELNUM));
		         params[2]=jsonData.toString();
		         rt_shadow.setVisibility(View.VISIBLE);
		     
		         new HttpPostTask().execute(params);
                     				
			}
		});
		
		}
	
	
	
	 private class ParentListAdapter extends BaseAdapter {
			
		    private LayoutInflater layoutInflater;  
		    private Context context;  
		    
		public ParentListAdapter(Context context) {
				super();
				this.context = context;
			    this.layoutInflater=LayoutInflater.from(context); 
			}
		
		
		final class Zujian{  
		    public TextView id,supplier,customer;  
	        public ListView list;      
	     }   

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			 return orderJA.size();  
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			 return orderJA.getJSONObject(position);  
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position; 
		}
	  
		@Override
		public View getView(int position, View  convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int selectID = position;   
			 Zujian zj=null;  
		        if(convertView==null){  
		            zj=new Zujian();  
		            //获得组件，实例化组件  
		            convertView=layoutInflater.inflate(R.layout.list_parent_actabondomorder, null);  
		          
		            zj.id=(TextView) convertView.findViewById(R.id.tv_orderid_listparent_actabondom);
		            zj.supplier=(TextView) convertView.findViewById(R.id.tv_supplier_listparent_actabondom); 
		            zj.customer=(TextView) convertView.findViewById(R.id.tv_customer_listparent_actabondom);
		            zj.list= (ListView) convertView.findViewById(R.id.list_listparent_actabondom);
		            convertView.setTag(zj);  
		            System.out.println("position----"+position+"------inflated");
		        }else{   System.out.println("position----"+position+"-------not inflated");
		            zj=(Zujian)convertView.getTag();  
		        }  
		        //绑定数据  
		      //  zj.image.setBackgroundResource((Integer)data.getJSONObject(position).get("image"));  
		      
		        zj.id.setText("订单："+orderJA.getJSONObject(position).getLong(Order.ID)+""); 
		  
		        zj.supplier.setText("商家："+orderJA.getJSONObject(position).getString(Order.SERVICETELNUM)); 
		        zj.customer.setText("买家："+orderJA.getJSONObject(position).getString(Order.CUSTOMERTELNUM)); 
		        zj.list.setAdapter(new ChildListAdapter(context, position));
		        ListViewUtil.setListViewHeightBasedOnChildren(zj.list);
		        //打开箱格
		        String boxesIn=orderJA.getJSONObject(position).getString(Order.BOXESIN);
		        List<Integer> boxes= new ArrayList<Integer>();
				 for(int i=0;i<boxesIn.length()/3;i++){
					 int boxID=Integer.parseInt(boxesIn.substring(i*3,(i+1)*3));
					boxes.add(boxID);
					
				 }
				 Message msg = new Message();              
                 msg.what=1;
                 msg.obj=boxes;
                 Box.childHander.sendMessage(msg);
                 
		        return convertView;  
		} // end of getview()
		
		
		
		
		
	} //end of Adapter
	 
	 
	 private class ChildListAdapter extends BaseAdapter {
			
		    private LayoutInflater layoutInflater;  
		    private Context context;  
		    private int PARENT_POSITION ;
		    
		public ChildListAdapter(Context context,int position) {
				super();
				this.context = context;
			    this.layoutInflater=LayoutInflater.from(context); 
			    this.PARENT_POSITION= position;
			}
		
		
		final class Zujian{  
		    public TextView box;  
	        public Button reopen;      
	     }   

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			 return orderJA.getJSONObject(PARENT_POSITION).getString(Order.BOXESIN).length()/3;  
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			 return position;  
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position; 
		}
	  
		@Override
		public View getView(int position, View  convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int selectID = position;   
			 Zujian zj=null;  
		        if(convertView==null){  
		            zj=new Zujian();  
		            //获得组件，实例化组件  
		            convertView=layoutInflater.inflate(R.layout.list_child_actabondomorder, null);  
		            zj.box= (TextView) convertView.findViewById(R.id.tv_boxid_listchild_actobondomorder);
		            zj.reopen=  (Button) convertView.findViewById(R.id.btn_reopen_listchild_actobondomorder);
		            convertView.setTag(zj);  
		            System.out.println("position----"+position+"------inflated");
		        }else{   System.out.println("position----"+position+"-------not inflated");
		            zj=(Zujian)convertView.getTag();  
		        }  
		        //绑定数据  
		      //  zj.image.setBackgroundResource((Integer)data.getJSONObject(position).get("image")); 
		       String boxStr= orderJA.getJSONObject(PARENT_POSITION).getString(Order.BOXESIN).substring(selectID*3,(1+selectID)*3);	       
		      final int boxID=Integer.parseInt( boxStr);
		       zj.box.setText("箱号："+ boxID);
		       zj.reopen.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
					
						 Message msg = new Message();              
		                 msg.what=1;
		                 List<Integer> boxes=new ArrayList<Integer>();
		                 boxes.add(boxID);
		                 msg.obj=boxes;
		                 Box.childHander.sendMessage(msg);
		               
			                 } 
				});
		       
		        return convertView;  
		} // end of getview()
		
		
		
	} //end of Adapter
	
	 private  class HttpPostTask extends android.os.AsyncTask<String,String,Map<String,Object>>{

			

			@Override
			protected Map<String,Object> doInBackground(String... params) {
				// TODO Auto-generated method stub
				 Map<String,Object> map = new HashMap<String ,Object>();		
			  map =	UniversalHttpPost.doPost(params);	             
				return map;
			}
			
			@Override
			protected void onPostExecute(Map<String,Object> map) {
					
				 System.out.println("-----------onPostExecute()--------------");
				 rt_shadow.setVisibility(View.GONE);
				 String PostResult=(String) map.get("PostResult");		 
				 boolean networkstate=(Boolean) map.get("PostState");
				 if(!networkstate){
					 CommonFunction.alert(TakebackAct.this, "失败", "无网络连接");return;
			      
				}
				//	Toast.makeText(DepositAct.this, "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				    JSONObject json = null;
				    int resultCode=-1;
					String resultInfo="";
					String affair="";				
					JSONObject jo;
					try{
				     json= JSONObject.fromObject(PostResult);
				     resultCode=json.getInt("resultCode");
				     resultInfo=json.getString("resultInfo");	
				     affair =json.getString("affair");	
				     jo= json.getJSONObject("jo");
					}catch(JSONException e){
						 CommonFunction.alert(TakebackAct.this, "失败", "数据解析错误");return;
					}
					if(affair.equals(AFFAIR_TAKEBACK_ORDER)){
						if(resultCode==2){
							JSONArray orderTakebacked= jo.getJSONArray("orders");
							for(int j=0;j<orderTakebacked.size();j++){
								long orderid= orderTakebacked.getJSONObject(j).getLong(Order.ID);
							for(int i=0;i<orderJA.size();i++){
								if(orderJA.getJSONObject(i).getLong(Order.ID)==orderid){
									 orderJA.remove(i);									
									//更改数据库
								     new OrderDao(TakebackAct.this).updateOrderState(orderid, 23);
									break;
								      }
							       }
							}
							 Intent intent= new Intent(TakebackAct.this, AbandomAct.class);
						      startActivity(intent);
						      TakebackAct.this.finish();
							   return;	 
						}else{
							 CommonFunction.alert(TakebackAct.this, "失败", resultInfo);return;	
						}					
					}
					
			       
				
			} //onPostExecute
		} //AsyncTask
}
